package org.example.springboot3.service.impl;

import org.example.springboot3.service.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileStorageImpl implements FileStorageService {
    @Value("${spring.servlet.multipart.location}")
    private String uploadDir;

    @Override
    public String storeFile(MultipartFile file) {
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        Path targetLocation = Paths.get(uploadDir).resolve(fileName);
        try {
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            // 处理文件存储异常
            return null;
        }
        return fileName;
    }
    public boolean deleteFile(String fileName) {
        String filePath = uploadDir + fileName;
        Path path = Path.of(filePath);
        try {
            Files.deleteIfExists(path);
            return true;
        } catch (Exception e) {
            // 记录日志或抛出异常
            return false;
        }
    }
}